﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.Linq.SqlClient;

public partial class Operator_LatePayments : System.Web.UI.Page
{
    BankDataDataContext db = new BankDataDataContext();

    protected decimal getMonthAmount(int contractId)
    {
        Contract selectedContract = getContract(contractId);
        if (selectedContract != null)
        {
            decimal amount = (selectedContract.Amount - getPayedMainAmount(contractId)) / (selectedContract.TermLength - getMonthCountPayment(contractId));
            return amount;
        }
        return -1;
    }

    protected decimal getPayedMainAmount(int contractId)
    {
        var payments = from payment in db.ContractPayments where payment.ConractId == contractId select payment;
        decimal payedAmount = 0;
        foreach (ContractPayment contractPayment in payments)
        {
            payedAmount += contractPayment.MainAmount;
        }
        return payedAmount;
    }

    protected decimal getPayedPercentageAmount(int contractId)
    {
        var payments = from payment in db.ContractPayments where payment.ConractId == contractId select payment;
        decimal payedAmount = 0;
        foreach (ContractPayment contractPayment in payments)
        {
            payedAmount += contractPayment.PercentageAmount;
        }
        return payedAmount;
    }

    protected double getMonthCreditPercentage(int contractId)
    {
        Contract contract = getContract(contractId);
        var creditCurrencies = from creditCurrency in db.CreditCurrencies
                               where creditCurrency.CreditId == contract.CreditId &&
                                   creditCurrency.CurrencyId == contract.CurrencyId
                               select creditCurrency;
        return creditCurrencies.First().Percentage / 12;
    }

    protected int getMonthCountFromLastPayment(int contractId)
    {
        var payments = from payment in db.ContractPayments where payment.ConractId == contractId select payment;
        Contract contract = getContract(contractId);
        DateTime maxDate = contract.CreationDate;
        foreach (ContractPayment contractPayment in payments)
        {
            if (contractPayment.Date > maxDate)
            {
                maxDate = contractPayment.Date;
            }
        }
        return SqlMethods.DateDiffMonth(maxDate, DateTime.Now);
    }

    protected int getMonthCountPayment(int contractId)
    {
        var payments = from payment in db.ContractPayments where payment.ConractId == contractId select payment;
        Contract contract = getContract(contractId);
        DateTime maxDate = contract.CreationDate;
        foreach (ContractPayment contractPayment in payments)
        {
            if (contractPayment.Date > maxDate)
            {
                maxDate = contractPayment.Date;
            }
        }
        return SqlMethods.DateDiffMonth(contract.CreationDate, maxDate);
    }

    protected Contract getContract(int contractId)
    {
        var contracts = from contract in db.Contracts where contract.ContractId == contractId select contract;
        if (contracts.Count() > 0)
        {
            return contracts.First();
        }
        return null;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("Operator"))
        {
            Response.Redirect("~/Account/Login.aspx");
        }
        else
        {
            SqlDataSourceLatePayments.SelectParameters["OperatorId"].DefaultValue = getOperatorId().ToString();
        }
    }

    protected int getOperatorId()
    {
        var operators = from bankOperator in db.Operators where bankOperator.UserId == (Guid)Membership.GetUser().ProviderUserKey select bankOperator;
        return operators.First().OperatorId;
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string contractId = GridView1.DataKeys[GridView1.SelectedIndex]["ContractId"].ToString();
        if (contractId != null)
        {
            var contracts = from contract in db.Contracts where contract.ContractId == Convert.ToInt32(contractId) select contract;
            Contract selectedContract = contracts.First();
            selectedContract.LastNotificationLatePaymentDate = DateTime.Now;
            db.SubmitChanges();
            MailServer server = new MailServer();
            server.sendMailAboutDebt(selectedContract.Company.UserProfiles.First().CompanyEmail, selectedContract.Credit.Name,
                GridView1.Rows[GridView1.SelectedIndex].Cells[8].Text, selectedContract.Currency.Name);
            Response.Redirect("~/Operator/LatePayments.aspx");
        }
    }
    protected void GridView1_DataBinding(object sender, EventArgs e)
    {
        SqlDataSourceLatePayments.SelectParameters["OperatorId"].DefaultValue = getOperatorId().ToString();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            int contractId = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex]["ContractId"].ToString());
            Contract selectedContract = getContract(contractId);
            decimal paymentAmount = Math.Round((getMonthAmount(contractId) + (selectedContract.Amount - getPayedMainAmount(contractId))
                * (decimal)(getMonthCreditPercentage(contractId) / 100)) * getMonthCountFromLastPayment(contractId), 2);
            if (paymentAmount > 0)
            {
                e.Row.Cells[7].Text = paymentAmount.ToString();
            }
            else
            {
                e.Row.Visible = false;
            }
        }        
    }
}